/**
 * Created by user on 2016-07-19.
 */
import * as bodyParser from 'body-parser';
import * as config from 'config';
import * as flash from 'connect-flash';
import * as cors from 'cors';
import * as express from 'express';
import {graphiqlExpress, graphqlExpress} from 'graphql-server-express'
import * as mongoose from 'mongoose'
import * as morgan from 'morgan'
import * as ms from 'ms'
import {Passport} from 'passport';
import * as qiniu from 'qiniu'
import * as request from 'request';
import * as superagent from 'superagent'
import GMModel from '../database/models/gm'
import configApi from './config-api'
import schema from './graphql/'


const app = express();
export default app


if (process.env.NODE_ENV !== 'production') {
  app.use(morgan('dev'));
}


app.use(bodyParser.json()); // get information from html forms
app.use(bodyParser.urlencoded({extended: false}));
app.use(cors({
  origin: config.get('gm-tool.allowOrigin'),
  credentials: true,
}));

const passport = new Passport()
app.use(passport.initialize())
app.use(flash())
configApi(app, passport)

app.get('/head', cors(), function (req, res) {
  let url = req.query.url || ''
  url = url.replace('.png', '') || 'http://wx.qlogo.cn/mmopen/vi_32/PiajxSqBRaEIrBEU3kqpPyp5DaY7bibfhEic2CuWdDFEjN9UJqcPeKmvhmK8RVLfjiaM2oKicAgrMNY0AicuSkZPR2ibQ/0'
  try {
    const x = request.get(encodeURI(url))
    x.on('error', () => {
    })
    x.pipe(res)
      .on('error', () => {

      })
  } catch (error) {
    console.error('error', error)
  }
})

const allPass = (req, res, next) => next()

const accessKey = 'A5Qp7L1Jlbe93UF4-vuxFWg9VGMRCZXaR932EUAZ';
const secretKey = '0oB9ZzZ0hiubdZ-oHzrlg5GZhEv5SyFbgkgtL1Oz';
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
const options = {
  scope: 'ulonggame',
  expires: 600
};
const putPolicy = new qiniu.rs.PutPolicy(options);

app.post('/uploadToken', function (req, res) {
  const token = putPolicy.uploadToken(mac)
  res.json({token})
})


const authMiddleWare = passport.authenticate('jwt')

app.use('/graphql', authMiddleWare, bodyParser.json(),
  graphqlExpress(
    request => ({schema, context: {request}})
  )
);

if (process.env.NODE_ENV !== "production") {
  app.use('/graphql-dev', bodyParser.json(),
    graphqlExpress(
      request => ({schema, context: {request}})
    )
  )
  app.use('/graphiql', graphiqlExpress({endpointURL: '/graphql-dev'}));
}

app.get('/wechat/login', async (req, res) => {

  const wxCode = req.query.code

  console.log(req.query)
  if (wxCode) {

    try {
      const wechatRes = await superagent
        .get('https://api.weixin.qq.com/sns/jscode2session')
        .query({
          appid: config.get("openWechat.weChatId"),
          secret: config.get("openWechat.weChatSecret"),
          js_code: wxCode,
          grant_type: 'authorization_code'
        })
      const {text} = wechatRes

      res.json({
        ok: true,
        accessToken: JSON.parse(text)
      })
    } catch (e) {
      res.json({ok: false, info: '登录失败'})
    }
  } else {

    res.json({ok: false, info: '非法的 code'})
  }
})


if (!module.parent) {
  startup()
}


async function startup() {
  const port = config.get('gm-tool.port')

  connectMongo()
  await initSuperAccounts();
  await app.listen(port)
  console.log(`${__filename}:77 startup on ${port} ...`)
}

function connectMongo() {
  console.log(`Trying to connect to\t${config.get("database.url")}\t ...\n`)
  if (mongoose.connection.readyState !== 1) {
    mongoose.connect(config.get('database.url'), {
      useNewUrlParser: true,
      reconnectTries: Number.MAX_VALUE,
      reconnectInterval: ms('1s'),
      connectTimeoutMS: ms('5s')
    })
  }
}


export async function initSuperAccounts() {
  const superAccounts = config.get('gm-tool.superAccounts');

  for (const account of superAccounts) {
    const {username, password} = account;
    let gm = await GMModel.findOne({username});
    if (gm) {
      continue;
    }
    gm = new GMModel({username, role: 'super'});
    gm.password = GMModel.generateHash(password);
    gm.save();
  }
}



